<template>
  <view class="staff-detail-page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <u-loading-icon mode="circle" size="28" color="#409EFF"></u-loading-icon>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 详情内容 -->
    <scroll-view v-else-if="staffInfo && Object.keys(staffInfo).length > 0" 
                 scroll-y="true" 
                 class="detail-scroll" 
                 :style="{ height: scrollViewHeight }">
      
      <!-- 状态卡片 -->
      <view class="status-card">
        <view class="status-header">
          <view class="status-icon" :class="getStatusIconClass(staffInfo?.status)">
            <u-icon :name="getStatusIcon(staffInfo?.status)" color="#fff" size="24"></u-icon>
          </view>
          <view class="status-info">
            <text class="status-text">{{ getStatusText(staffInfo?.status) }}</text>
            <text class="status-desc">{{ getStatusDescription(staffInfo?.status) }}</text>
          </view>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="info-section">
        <view class="section-title">
          <u-icon name="info-circle" size="16" color="#333"></u-icon>
          <text class="title-text">基本信息</text>
        </view>
        
        <view class="info-list">
          <view class="info-item">
            <text class="info-label">姓名</text>
            <text class="info-value">{{ staffInfo?.realName || '--' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">工号</text>
            <text class="info-value">{{ staffInfo?.employeeNo || '--' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">职位</text>
            <text class="info-value">{{ staffInfo?.position || '--' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">物业公司</text>
            <text class="info-value">{{ staffInfo?.propertyCompanyName || '--' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">手机号</text>
            <text class="info-value">{{ staffInfo?.phone || '--' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">邮箱</text>
            <text class="info-value">{{ staffInfo?.email || '--' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">入职日期</text>
            <text class="info-value">{{ formatDate(staffInfo?.entryDate) || '--' }}</text>
          </view>
        </view>
      </view>

      <!-- 工作信息 -->
      <view class="info-section">
        <view class="section-title">
          <u-icon name="briefcase" size="16" color="#333"></u-icon>
          <text class="title-text">工作信息</text>
        </view>
        
        <view class="info-list">
          <view class="info-item">
            <text class="info-label">工作状态</text>
            <text class="info-value">{{ getWorkStatusText(staffInfo?.workStatus) }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">最后签到</text>
            <text class="info-value">{{ formatDateTime(staffInfo?.lastCheckIn) || '--' }}</text>
          </view>
          <view class="info-item">
            <text class="info-label">本月出勤</text>
            <text class="info-value">{{ staffInfo?.monthlyAttendance || '--' }}天</text>
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="action-section">
        <u-button 
          type="primary" 
          text="考勤记录"
          size="large"
          @click="handleAttendance"
        />
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view v-else class="empty-state">
      <u-icon name="info-circle" size="48" color="#ccc"></u-icon>
      <text class="empty-text">暂无员工信息</text>
    </view>
  </view>
</template>

<script setup>
/**
 * 员工详情页面
 * 严格按照《App端编码规范权威标准声明.md》规范实现
 * 参考维修详情页面风格，构建简洁大方的详情页面
 * 按生产环境高标准编写代码
 * 
 * @author Wu.Liang
 * @date 2025-01-30
 */

import { ref, onMounted, computed } from 'vue'
import { staffApi } from '@/api/staff'

// 响应式数据
const loading = ref(false)
const staffInfo = ref(null)
const staffId = ref(null)

// 计算滚动视图高度
const scrollViewHeight = ref('calc(100vh - 120px)')

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    1: '在职',
    0: '离职',
    2: '待入职'
  }
  return statusMap[status] || '未知'
}

// 获取状态描述
const getStatusDescription = (status) => {
  const descMap = {
    1: '员工正常工作状态',
    0: '员工已离职',
    2: '员工待入职状态'
  }
  return descMap[status] || '状态描述'
}

// 获取状态图标
const getStatusIcon = (status) => {
  const iconMap = {
    1: 'checkmark-circle',
    0: 'close-circle',
    2: 'clock'
  }
  return iconMap[status] || 'clock'
}

// 获取状态图标样式类
const getStatusIconClass = (status) => {
  const classMap = {
    1: 'status-icon-active',
    0: 'status-icon-inactive',
    2: 'status-icon-pending'
  }
  return classMap[status] || 'status-icon-pending'
}

// 获取工作状态文本
const getWorkStatusText = (workStatus) => {
  const workStatusMap = {
    1: '正常',
    2: '请假',
    3: '出差',
    4: '调休'
  }
  return workStatusMap[workStatus] || '未知'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return ''
  const d = new Date(dateTime)
  return d.toLocaleString('zh-CN')
}

// 页面加载时计算高度
const calculateScrollHeight = () => {
  const systemInfo = uni.getSystemInfoSync()
  const windowHeight = systemInfo.windowHeight
  const navbarHeight = 44 // 导航栏高度
  const padding = 16 // 底部边距
  
  // 动态计算操作按钮区域高度
  let actionSectionHeight = 80 // 操作按钮区域高度（移除编辑按钮后减少）
  
  const calculatedHeight = windowHeight - navbarHeight - padding - actionSectionHeight
  scrollViewHeight.value = `${calculatedHeight}px`
  console.log('计算滚动高度:', calculatedHeight, 'px')
}

// 加载员工详情
const loadStaffDetail = async () => {
  console.log('loadStaffDetail开始执行，staffId:', staffId.value)
  if (!staffId.value) return
  
  loading.value = true
  
  try {
    const response = await staffApi.getStaffDetail(staffId.value)
    console.log('getStaffDetail响应:', response)
    
    if (response && response.code === 200 && response.data) {
      staffInfo.value = response.data
      console.log('staffInfo设置成功:', staffInfo.value)
      
      // 重新计算滚动高度
      calculateScrollHeight()
    } else {
      staffInfo.value = null
      uni.showToast({
        title: response?.message || '加载失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('加载员工详情失败:', error)
    staffInfo.value = null
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    console.log('loadStaffDetail完成，loading:', loading.value)
  }
}

// 查看考勤记录
const handleAttendance = () => {
  uni.navigateTo({
    url: `/pages/property-work/attendance-record?staffId=${staffId.value}`
  })
}

// 页面加载时初始化数据
onMounted(() => {
  try {
    // 计算滚动视图高度
    calculateScrollHeight()
    
    // 获取页面参数
    let id = null
    
    // 方式1: 通过getCurrentPages获取
    try {
      const pages = getCurrentPages()
      const currentPage = pages[pages.length - 1]
      if (currentPage && currentPage.options && currentPage.options.id) {
        id = currentPage.options.id
      }
    } catch (e) {
      console.log('getCurrentPages方式获取参数失败:', e)
    }
    
    // 方式2: 通过URL解析获取
    if (!id) {
      try {
        const url = window.location.href
        const urlParams = new URLSearchParams(url.split('?')[1])
        id = urlParams.get('id')
      } catch (e) {
        console.log('URL解析方式获取参数失败:', e)
      }
    }
    
    if (!id) {
      throw new Error('无法获取员工ID参数')
    }
    
    const parsedId = parseInt(id)
    if (isNaN(parsedId)) {
      throw new Error('无效的ID参数')
    }
    
    staffId.value = parsedId
    console.log('获取到员工ID:', staffId.value)
    
    // 先计算初始高度
    calculateScrollHeight()
    
    // 然后加载详情数据
    loadStaffDetail()
  } catch (error) {
    console.error('页面初始化失败:', error)
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    })
    setTimeout(() => {
      uni.navigateBack()
    }, 1500)
  }
})
</script>

<style lang="scss" scoped>
.staff-detail-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  overflow: visible;
  position: relative;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f5f5;
}

.loading-text {
  margin-top: 12px;
  font-size: 14px;
  color: #666;
}

.detail-scroll {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 16px;
  min-height: 0;
  padding-bottom: 20px;
}

.status-card {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.status-header {
  display: flex;
  align-items: center;
}

.status-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  
  &.status-icon-active {
    background-color: #67C23A;
  }
  
  &.status-icon-inactive {
    background-color: #F56C6C;
  }
  
  &.status-icon-pending {
    background-color: #E6A23C;
  }
}

.status-info {
  flex: 1;
}

.status-text {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  display: block;
  margin-bottom: 4px;
}

.status-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.info-section {
  background-color: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.title-text {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-left: 8px;
}

.info-list {
  .info-item {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    padding: 12px 0;
    border-bottom: 1px solid #f8f8f8;
    
    &:last-child {
      border-bottom: none;
    }
  }
  
  .info-label {
    font-size: 14px;
    color: #666;
    min-width: 80px;
    flex-shrink: 0;
  }
  
  .info-value {
    font-size: 14px;
    color: #333;
    text-align: right;
    flex: 1;
    margin-left: 16px;
  }
}

.action-section {
  padding: 20px 0;
  margin-top: 16px;
  min-height: 0;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f5f5;
}

.empty-text {
  font-size: 14px;
  color: #999;
  margin-top: 12px;
}

/* 响应式适配 */
@media screen and (max-width: 375px) {
  .detail-scroll {
    padding: 12px;
  }
  
  .info-section {
    padding: 16px;
  }
}
</style>
